package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.dto.DtsSerachDto;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * projectName: shop-manage
 *
 * @author: 元
 * time: 2021/9/14 0014 20:41
 * description:阿里云OSS对象存储
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    //对象存储分页查询 模糊查询
    @RequestMapping("list")
    public Object list(DtsSerachDto serachDto){

        Map data = storageService.selectByPage(serachDto);

        return ResponseUtil.ok(data);
    }

    //文件上传,本地文件上传到阿里云OSS
    @RequestMapping("create")
    public Object create(@RequestParam("file") MultipartFile file)throws Exception{

        //1.获取文件名
        String originaFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originaFilename)){
            throw new RuntimeException("上传文件为空, 不允许上传!");
        }
        //2. 获取文件扩展名
        String ext = originaFilename.substring(originaFilename.lastIndexOf("."));

        //3. 调用service完成上传和存储
        DtsStorage dtsStorage = storageService.add(originaFilename,ext,(int)file.getSize(),file.getBytes());

        return ResponseUtil.ok(dtsStorage);
    }

    //删除阿里云oss存储对象
    @RequestMapping("delete")
    public Object delete(@RequestBody DtsStorage dtsStorage){
        int rows = storageService.deleteById(dtsStorage.getId());
        if (rows == 0){
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok();

    }


    //修改阿里云oss存储对象
    @RequestMapping("update")
    public Object update(@RequestBody DtsStorage dtsStorage){
        int rows = storageService.updateStoarge(dtsStorage);
        if (rows == 0){
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok();
    }


}
